package com.example.spring_mysql.exception

import jakarta.validation.ConstraintViolationException
import org.springframework.context.i18n.LocaleContextHolder
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice


@RestControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException::class)
    fun handleValidException(ex: MethodArgumentNotValidException): ResponseEntity<String> {
        println("handleValidException"+ex)
        val msg = StringBuilder()
        for (error in ex.allErrors) {
            msg.append(", ")
            msg.append(if (error.defaultMessage == null) "" else error.defaultMessage)
        }
        return ResponseEntity.badRequest().body( msg.substring(2))
    }

    @ExceptionHandler(ConstraintViolationException::class)
    fun handleConstraintViolation(ex: ConstraintViolationException): ResponseEntity<String> {
        println("ConstraintViolationException"+ex.constraintViolations)
        val errors = ex.constraintViolations.associate { violation ->
            println("violation:$violation")
            val propertyPath = violation.propertyPath.toString()
            val message = violation.messageTemplate // 这个才是你写在注解上的原始 message
            propertyPath to message
        }

        return ResponseEntity.badRequest().body(errors.toString())
    }

    // 处理运行时异常
    @ExceptionHandler(RuntimeException::class)
    fun handleRuntimeException(ex: RuntimeException): ResponseEntity<String> {
        return ResponseEntity
            .status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body("服务器内部错误: " + ex.message)
    }

//    // 处理所有异常（兜底）
//    @ExceptionHandler(Exception::class)
//    fun handleException(ex:Exception): ResponseEntity<String> {
//        return ResponseEntity
//            .status(HttpStatus.INTERNAL_SERVER_ERROR)
//            .body("未知错误: " + ex.message)
//    }
}
